package com.pingan.pastry.rpc.util;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * HTTP 执行器，封装了连接池，超时熔断机制
 *
 * @Author longcheng
 * @Date 2021/06/20
 */
public class HttpClientUtil {

    private static int RESPONSE_SUCCESS_CODE = 200;

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientUtil.class);

    /**
     * 1. 连接池
     * 2. 封装get/post，以及callback异步调用 方法
     */
    public static String processGet(String url, int connectionTimeout, int socketTimeout) throws Exception {
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpClient client = HttpClientBuilder.create().build();
        RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(connectionTimeout).setSocketTimeout(socketTimeout).build();
        httpGet.setConfig(config);
        return processRequest(client, httpGet);
    }

    public static String processPost(String url, String param, String contentType, int connectionTimeout, int socketTimeout) throws Exception {
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpClient client = HttpClientBuilder.create().build();
        RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(connectionTimeout).setSocketTimeout(socketTimeout).build();
        httpPost.setConfig(config);
        HttpEntity params = buildParam(param, contentType);
        httpPost.setEntity(params);
        return processRequest(client, httpPost);
    }

    private static HttpEntity buildParam(String params, String contentType) throws UnsupportedEncodingException {
        StringEntity paramEntity = new StringEntity(params, "UTF-8");
        paramEntity.setContentEncoding("UTF-8");
        paramEntity.setContentType(contentType);
        return paramEntity;

        /*List<NameValuePair> formParams = new ArrayList<>();
        Set<Map.Entry<String, String>> entries = paramMap.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            NameValuePair nameValuePair = new BasicNameValuePair(entry.getKey(), entry.getValue());
            formParams.add(nameValuePair);
        }
        HttpEntity reqEntity = new UrlEncodedFormEntity(formParams, "utf-8");
        return reqEntity;*/
    }

    public static String processRequest(CloseableHttpClient httpClient, HttpRequestBase requestBase) throws Exception {
        String result = null;
        CloseableHttpResponse closeableHttpResponse = null;
        try {
            closeableHttpResponse = httpClient.execute(requestBase);
            HttpEntity entity = closeableHttpResponse.getEntity();
            if (closeableHttpResponse != null) {
                int responseCode = closeableHttpResponse.getStatusLine().getStatusCode();
                if (responseCode == RESPONSE_SUCCESS_CODE) {
                    result = EntityUtils.toString(entity);
                }
            }
            return result;
        } catch (IOException e) {
            LOGGER.error("remote httpGet failed:" + e.getMessage());
            throw new Exception("remote httpGet failed:" + e.getMessage());
        } finally {
            httpClient.close();
            if (closeableHttpResponse != null) {
                closeableHttpResponse.close();
            }
        }
    }

}
